package com.hj.hos.service;

import com.hj.hos.HosService;
import com.hj.hos.properties.HosMinioProperties;
import com.hj.hos.properties.HosProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author hj
 * @Date 2023/4/29
 * @Description: Minio存储
 */
public class MinioHosService extends HosService {

    private final MinioClient minioClient;

    public MinioHosService(HosProperties properties) {
        this.properties = properties;
        HosMinioProperties minio = properties.getMinio();
        minioClient = MinioClient.builder().endpoint(minio.getEndPoint(),
                        minio.getPort(), minio.getSecure())
                .credentials(minio.getAccessKey(), minio.getSecretKey()).build();
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        HosMinioProperties minio = properties.getMinio();
        try {
            //如果BucketName不存在，则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minio.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minio.getBucketName()).build());
            }

            String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
            Optional<MediaType> mediaType = MediaTypeFactory.getMediaType(path);
            if (mediaType.isPresent()) {
                contentType = mediaType.get().toString();
            }

            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minio.getBucketName())
                            .contentType(contentType)
                            .object(path)
                            .stream(inputStream, inputStream.available(), -1)
                            .build()
            );

        } catch (Exception e) {
            throw new RuntimeException("Minio存储--上传文件失败：", e);
        }
        return minio.getAccessPrefix() + path;
    }


}
